package com.business.api.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.business.api.user.dto.UserDTO;
import com.business.api.user.from.UpdateUserInfoFrom;
import com.business.api.user.from.UserResetPasswordFrom;
import com.business.api.user.service.UserApiService;
import com.business.api.user.vo.data.UserDetailVO;
import com.seed.core.exception.ServiceException;
import com.seed.core.pojo.dto.SeedMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * @author gchiaway
 * 日期: 2020-06-11
 * 时间: 13:08
 */

@Slf4j
@Service("userApiService")
@Transactional(rollbackFor = ServiceException.class)
public class UserApiServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements UserApiService {


    /**
     * 重设密码
     *
     * @param userResetPasswordFrom 重设密码表单
     * @return 操作结果
     * @throws ServiceException 业务层异常
     */
    @Override
    @CacheEvict(value = {CacheConstant.SYS_USERS_CACHE}, allEntries = true)
    public SeedMessageDTO resetPassword(UserResetPasswordFrom userResetPasswordFrom) throws ServiceException {
        SeedMessageDTO result = new SeedMessageDTO();
        String username;
        SysUser user;
        try {
            user = this.baseMapper.selectById(userResetPasswordFrom.getUserId());
            username = user.getUsername();
        } catch (Exception e) {
            throw new ServiceException(e, userResetPasswordFrom);
        }
        String oldPassword = userResetPasswordFrom.getOldPassword();
        String passwordEncode = PasswordUtil.encrypt(username, oldPassword, user.getSalt());
        if (!user.getPassword().equals(passwordEncode)) {
            result.setSuccess(false);
            result.setCode("A0500");
            result.setMessage("旧密码输入错误!");
            return result;
        }
        String newPassword = userResetPasswordFrom.getNewPassword();
        if (oConvertUtils.isEmpty(newPassword)) {
            result.setSuccess(false);
            result.setCode("A0500");
            result.setMessage("新密码不允许为空!");
            return result;
        }
        String confirmPassword = userResetPasswordFrom.getConfirmPassword();
        if (!newPassword.equals(confirmPassword)) {
            result.setSuccess(false);
            result.setCode("A0500");
            result.setMessage("两次输入密码不一致!");
            return result;
        }
        try {
            String password = PasswordUtil.encrypt(username, newPassword, user.getSalt());
            int updateCount = this.baseMapper.update(new SysUser().setPassword(password), new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId()));
            if (updateCount <= 0) {
                result.setSuccess(false);
                result.setCode("A0500");
                result.setMessage("更新失败!");
                return result;
            }
        } catch (Exception e) {
            throw new ServiceException(e, userResetPasswordFrom);
        }
        return result;
    }

    /**
     * 根据用户id获取用户信息
     *
     * @param userId 用户id
     * @return 用户信息
     * @throws ServiceException 业务层异常
     */
    @Override
    public UserDTO getDetail(String userId) throws ServiceException {
        SysUser user;
        try {
            user = this.baseMapper.selectById(userId);
        } catch (Exception e) {
            throw new ServiceException(e, userId);
        }
        UserDTO userDTO = new UserDTO();
        if (ObjectUtils.isEmpty(user)) {
            userDTO.setSuccess(false);
            userDTO.setCode("A0500");
            userDTO.setMessage("id信息有误");
            return userDTO;
        }
        UserDetailVO detailVO = new UserDetailVO();
        detailVO.setId(user.getId());
        detailVO.setAvatar(user.getAvatar());
        detailVO.setBirthday(user.getBirthday());
        detailVO.setEmail(user.getEmail());
        detailVO.setPhone(user.getPhone());
        detailVO.setRealname(user.getRealname());
        detailVO.setSex(user.getSex());

        userDTO.setDetailVO(detailVO);
        return userDTO;
    }

    /**
     * 更新用户信息
     *
     * @param userInfoFrom 信息表单
     * @return 用户信息
     * @throws ServiceException 业务层异常
     */
    @Override
    public UserDTO update(UpdateUserInfoFrom userInfoFrom) throws ServiceException {
        UserDTO userDTO = new UserDTO();
        //这个校验是否可以删除，感觉有点重复
        String userId = userInfoFrom.getId();
        if (ObjectUtils.isEmpty(userId)) {
            userDTO.setSuccess(false);
            userDTO.setMessage("id不能为空");
            return userDTO;
        }
        SysUser user;
        try {
            user = this.baseMapper.selectById(userId);
        } catch (Exception e) {
            throw new ServiceException(e, userInfoFrom);
        }
        if (ObjectUtils.isEmpty(user)) {
            userDTO.setSuccess(false);
            userDTO.setCode("A0500");
            userDTO.setMessage("id信息有误,查询用户不存在.");
            return userDTO;
        }
        //主键id
        user.setId(userInfoFrom.getId());
        //真实姓名
        user.setRealname(userInfoFrom.getRealname());
        //性别（1：男 2：女）
        user.setSex(userInfoFrom.getSex());
        //生日
        user.setBirthday(userInfoFrom.getBirthday());
        //电子邮件
        user.setEmail(userInfoFrom.getEmail());
        //电话
        user.setPhone(userInfoFrom.getPhone());
        //头像
        user.setAvatar(userInfoFrom.getAvatar());

        try {
            int updateCount = this.baseMapper.updateById(user);
            if (updateCount <= 0) {
                userDTO.setSuccess(false);
                userDTO.setCode("A0500");
                userDTO.setMessage("更新失败!");
                return userDTO;
            }
        } catch (Exception e) {
            throw new ServiceException(e, userInfoFrom);
        }
        UserDetailVO userDetailVO = this.getDetail(user.getId()).getDetailVO();
        userDTO.setDetailVO(userDetailVO);
        return userDTO;
    }
}
